# -*- coding: utf-8 -*-
# @Time    : 18-2-6 下午5:10
# @Author  : huanggz
# @Email   : 308602626@qq.com
# @File    : weibo_guest.py
# @Software: PyCharm
"""
微博自动关注
"""

import weibo_login
import requests
import re
from utils import get_mongo_collection

db_cookie = get_mongo_collection('weibo_cookie')
feed = get_mongo_collection('feed')
re_st = re.compile("st: '(.*)'")


# cookie 从库取
def get_cookie_from_mongo():
    cookie_conf = db_cookie.find_one()
    if not cookie_conf:
        cookie, cookie_srt = weibo_login.login('18101038354', 'qingdian123')
        db_cookie.insert({'cookie': 'SUB=' + cookie["SUB"] + ';', 'cookie_str': cookie_srt})
        cookie_conf = db_cookie.find_one()
    return cookie_conf


# cookie 登录得到cookie
def get_cooke_from_login(id):
    cookie, cookie_srt = weibo_login.login("18101038354", 'qingdian123')
    cookie_new = 'SUB=' + cookie["SUB"] + ';'
    db_cookie.update({"_id": id}, {"$set": {"cookie": cookie_new, 'cookie_str': cookie_srt}})
    return cookie_srt


def create(uid=2836557793):
    get_cookie_info = get_cookie_from_mongo()
    header = {
        'Cookie': get_cookie_info['cookie_str'],
        'Origin': 'https://m.weibo.cn',
        'Referer': f'https://m.weibo.cn/u/{uid}',
        'X-Requested-With': 'XMLHttpRequest',
        "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"
    }
    info = requests.get('https://m.weibo.cn/msg/index?format=cards', headers=header).json()
    if 'ok' in info:
        # cookie存库
        Cookie = get_cooke_from_login(get_cookie_info['_id'])
        header = {'Cookie': Cookie,
                  'Origin': 'https://m.weibo.cn',
                  'X-Requested-With': 'XMLHttpRequest',
                  'Referer': f'https://m.weibo.cn/u/{uid}',
                  "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.87 Safari/537.36"
                  }

    page_text = requests.get(f'https://m.weibo.cn/u/{uid}', headers=header).text
    st = re_st.search(page_text).group(1)
    data = {'uid': f'{uid}', 'st': st}
    info = requests.post('https://m.weibo.cn/api/friendships/create', data=data, headers=header).json()
    print(uid)
    print(info)


def main():
    feed = get_mongo_collection('feed')
    uid = []
    for f in feed.find({'purpose': '微博'}):
        if f['uid'] in uid or f.get('guest', 0) == 2:
            continue
        else:
            uid.append(f['uid'])
    times = 1
    # print(uid)
    for u in uid:
        create(u)
        feed.update_many({'uid': u}, {"$set": {'guest': 2}})
        times += 1
        if times > 10:
            break


if __name__ == '__main__':
    main()
